package cn.schoolwow.util.domain.beanCopy;

import cn.schoolwow.quickflow.QuickFlow;
import cn.schoolwow.quickflow.QuickFlowBuilder;
import cn.schoolwow.quickflow.domain.FlowContext;
import cn.schoolwow.util.module.beanCopy.flow.CopyPropertiesFlow;
import cn.schoolwow.util.module.beanCopy.flow.DeepCloneFlow;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import java.util.ArrayList;
import java.util.List;

public class BeanCopy {
    private static QuickFlow quickFlow = QuickFlowBuilder.newInstance();

    /**深克隆实例列表*/
    public static Object deepCloneObject(Object source){
        FlowContext flowContext = quickFlow.startFlow(new DeepCloneFlow())
                .putCurrentCompositeFlowData("source", source)
                .execute();
        Object cloneObject = flowContext.checkData("cloneObject");
        return cloneObject;
    }

    /**复制属性*/
    public static void copyProperties(Object source, Object target){
        quickFlow.startFlow(new DeepCloneFlow())
                .next(new CopyPropertiesFlow())
                .putCurrentCompositeFlowData("source", source)
                .putCurrentCompositeFlowData("target", target)
                .execute();
    }

    /**克隆实例*/
    public static <T> T cloneObject(Object source, Class<T> targetClass){
        if(null==source){
            return null;
        }
        String content = JSON.toJSONString(source);
        JSONObject sourceObject = JSON.parseObject(content);
        T targetInstance = sourceObject.toJavaObject(targetClass);
        return targetInstance;
    }

    /**克隆实例列表*/
    public static <T> List<T> cloneObjectList(List sourceList, Class<T> targetClass){
        if(null==sourceList){
            return null;
        }
        if(sourceList.isEmpty()){
            return new ArrayList<>();
        }
        String content = JSON.toJSONString(sourceList);
        List<T> targetInstanceList = JSON.parseArray(content).toJavaList(targetClass);
        return targetInstanceList;
    }

    /**克隆JSONObject*/
    public static JSONObject cloneJSONObject(JSONObject jsonObject){
        String content = jsonObject.toJSONString();
        JSONObject cloneJsonObject = JSON.parseObject(content);
        return cloneJsonObject;
    }

    /**克隆JSONArray*/
    public static JSONArray cloneJSONArray(JSONArray jsonArray){
        String content = jsonArray.toJSONString();
        JSONArray cloneJSONArray = JSON.parseArray(content);
        return cloneJSONArray;
    }

}
